package com.leyou.page.service;

import com.leyou.page.utils.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Service
public class FileService {

    @Value("${ly.thymeleaf.destPath}")
    private String destPath;

    //模板引擎
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private PageService pageService;

    /**
     * 判断文件夹下是否有指定
     * @param spuId
     * @return
     */
    public boolean exist(Long spuId) {
        File file = new File(destPath);
        if(!file.exists()){
            file.mkdirs();
            return false;
        }
        File file1 = new File(destPath, spuId + ".html");
        return file1.exists();
    }

    public void syncCreateHtml(Long spuId) {
        //使用多线程  产生页面静态化
        ThreadUtils.execute(()->{
            createHtml(spuId);
        });

    }

    private void createHtml(Long spuId) {
        //使用模板引擎
        //创建上下文对象
        Context context = new Context();
        context.setVariables(pageService.loadData(spuId));//吧数据存入context上下文
        File file = new File(destPath,spuId+".html");
        try {
            //创建printWriter对象
            PrintWriter printWriter = new PrintWriter(file,"utf-8");
            //产生html静态文件
            templateEngine.process("item",context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public void deleteHtml(Long id) {
        File file = new File(destPath, id + ".html");
        file.deleteOnExit();
    }
}
